<?php

namespace App\Jobs;

use App\Models\Book;
use App\Models\BookUpload;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use function App\Helpers\createdGuid;

class Bookjob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public $file_path = "";
    public $table_year = "";
    public $book_id = "";
    public $book_uni_code = "";
    public function __construct($path,$year,$book_id,$book_uni_code)
    {
        $this->file_path = $path;
        $this->table_year = $year;
        $this->book_id = $book_id;
        $this->book_uni_code = $book_uni_code;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $file_path = "./public/".$this->file_path;
        $data = (new Book())->fileCoverData($file_path);
        $chapter_list = $data['chapter_list'];
        $content_list = $data['content_list'];
        $total = count($chapter_list);
        $chapter_table = "chapter_".$this->table_year;
        $content_table = "content_".$this->table_year;
        $month = date("m",time());
        $created_at = date("Y-m-d H:i:s",time());
//        $chapter_id_arr = [];
        //先查询出来 这本书是否有章节存在
        $max_index = DB::table($chapter_table)->where('book_uni_code',$this->book_uni_code)->max("index");
        if(empty($max_index)){
            //没有章节存在 先处理一百条数据
            $start_num = 0;
            $for_num = 100;
        }else{
            $start_num = $max_index+1;
            $for_num = ($total-$start_num) > 100 ? 100+$start_num : $total;
        }
        if($total-$start_num <= 0){
            BookUpload::query()->where("book_id",$this->book_id)->update(['status' => 1]);
            return;//txt书籍全部上传完成
        }
        for($i = $start_num; $i<$for_num;$i++){
            $word =  mb_strlen($content_list[$i]);
            $chapter_data = [
                'book_id' => $this->book_id,
                'book_uni_code' => $this->book_uni_code,
                'uni_code' => createdGuid("chapter"),
                'name' => $chapter_list[$i],
                'index' => $i,
                'word' =>$word,
                'year' => $this->table_year,
                'month' => $month,
                'created_at' => $created_at
            ];
            $chapter_id = DB::table($chapter_table)->insertGetId($chapter_data);
            $content_data = [
                'chapter_id' => $chapter_id,
                'content' => $content_list[$i],
                'created_at' => $created_at,
            ];
            DB::table($content_table)->insert($content_data);
        }
    }
}
